import { Controller, Post, Body, Headers } from '@midwayjs/core';
import { validateDigest, fail, isPhone, sendSms } from '../utils/utils';

@Controller('/api')
export class APIController {
  @Post('/sms-send')
  async smsSend(@Body() body, @Headers() headers) {
    const validate = validateDigest(headers.appid, headers.digest);
    if(!validate) {
      return fail('Invalid digest', 401)
    }
    const { phone, content } = body
    if(!isPhone(phone)) {
      return fail('Invalid phone', 422)
    }
    if(!content) {
        return fail('Invalid content', 422)
    }
    const result = sendSms(phone, content);
    if(result.success) {
      return { success: true, message: 'OK', data: result.message };
    } else {
      return fail(result.message, 500)
    }
  }
}
